package com.niubility.controller;


import com.niubility.entity.Assess;

import com.niubility.entity.Message;
import com.niubility.entity.Users;
import com.niubility.exception.CustomException;
import com.niubility.server.Impl.ArticleServer;
import com.niubility.server.Impl.AssessServer;
import com.niubility.server.Impl.MessageServer;
import com.niubility.server.Impl.UsersService;
import com.niubility.vo.ArticleAll;
import com.niubility.vo.AssSendToUsers;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@Transactional(rollbackFor = Exception.class)
public class AssessController {
    Logger logger = Logger.getLogger("AssessController");
    @Resource
    private AssessServer assessServer;

    @Resource
    private MessageServer messageServer;

    @Resource
    private UsersService usersService;
    /*
    *@Author : John
    *@FinishDate : 2018-2-1
    *@Description :评论的存储
    */
    @Resource
    private ArticleServer articleServer;

    @RequestMapping("/AessessSave")
    public void Save(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        try {
            request.setCharacterEncoding("utf-8");
        }catch (IOException e){
            logger.debug("获取失败."+e);
        }
        int userId = 0;
        int artId = 0;
        String result;
        String callback = request.getParameter("callback");
        try {
            userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+103+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        try{
            artId = Integer.parseInt(request.getParameter("artId"));
        }catch (Exception e){
            result = callback+"({"+"\"returncode\""+":"+104+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }

        String assTest = request.getParameter("assCon");
       // ////System.out.println(assTest);
        Users users = usersService.LoadById(userId);
        ArticleAll articleAll = articleServer.SelectById(artId);
        String userName = users.getUserName();
        String userpic = users.getUserPicture();
        String artTitle = articleAll.getArtTitle();
        Assess assess = new Assess();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        assess.setArtId(artId);
        String text = "#"+userId+"#"+userName+"#"+userpic+"#"+artId+"#"+artTitle
                +"#"+assTest+"#"+userName+"评论了您的文章《"+artTitle+"》#";
       // ////System.out.println(text);
        assess.setAssText(text);
        assess.setUserId(userId);
        assess.setAssDate(dateFormat.format(new Date()));

        try {
            Message message = new Message();
            message.setMesMainid(articleAll.getAuthorId());
            message.setMesSendid(userId);
            message.setMesAssessmark(2);
            message.setMesText(text);
            message.setMesDate(dateFormat.format(new Date()));
            boolean bool = assessServer.Save(assess);
            messageServer.Save(message);
            result = callback + "({"+"\"returncade\":"+100+"})";
        }catch (Exception e){
            logger.debug("操作失败."+e);
            result = callback + "({"+"\"returncade\":"+108+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                logger.debug("数据传输错误."+e1);
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("传输失败."+e);
        }
    }
    /*
    *@Author : GongGeng
    *@FinishDate : 2018-2-1
    *@Description :获取评论
    */

    @RequestMapping("/AssLoadAll")
    public void AssLoadAll(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("utf-8");
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int num = Integer.parseInt(request.getParameter("num"));
        int artId = Integer.parseInt(request.getParameter("artId"));
        //System.out.println(num);
        String result = null;
        List<Assess> list = null;
        List<AssSendToUsers> user = new ArrayList<AssSendToUsers>();
        try {
            list = assessServer.LoadAllByNum(artId,num);
            for (Assess a:list) {
                String mess[] = a.getAssText().split("#");
                AssSendToUsers assSendToUsers = new AssSendToUsers();
                assSendToUsers.setUserId(Integer.parseInt(mess[1]));
                assSendToUsers.setUserName(mess[2]);
                assSendToUsers.setUserPic(mess[3]);
                assSendToUsers.setArtId(Integer.parseInt(mess[4]));
                assSendToUsers.setArtTitle(mess[5]);
                assSendToUsers.setAssText(mess[6]);
                assSendToUsers.setShowTop(mess[7]);
                assSendToUsers.setAssDate(a.getAssDate());
                user.add(assSendToUsers);
            }
            result = callback + "("+ JSONArray.fromObject(user).toString()+")";
        }catch (Exception e){
            logger.debug("获取失败."+e);
            result = callback + "({"+ "\"returncade\":"+108+"})";
            try {
                response.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            response.getWriter().write(result);
        }catch (Exception e){
            logger.debug("传输失败."+e);
        }
    }
}
